#include "InSdkCurl.h"

#define DEF_TAG             "Curl"

size_t Ext_InSdk_Curl_Https_Write_Data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
    size_t written = fwrite(ptr, size, nmemb, stream);
    //PRT_NORMAL("%s recv %d size, %d nmemb\n", __FUNCTION__, size, nmemb);
    return written;
}

int Ext_InSdkCurl_FileDownload(char *url, char *file_path)
{
    int ret = -1;
    CURL *curl = curl_easy_init();
    FILE *fp = fopen(file_path, "wb");
    /** HTTP报文头 **/
    struct curl_slist* headers = NULL;

    if (curl && fp)
    {
        /** 不检查ssl，可访问https **/
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
        /** HTTP报文填充 **/
        /** 添加HTTP的包头 Expect：防止数据大于1024个字节 需要等待服务响应 **/
        headers = curl_slist_append(headers, "Expect:");
        /** 接收所有类型的数据回复 **/
        headers = curl_slist_append(headers, "Accept: */*");
        /** 改成具体项目型号，User-Agent不填可能会被反爬虫限制 **/
        headers = curl_slist_append(headers,"User-Agent: pumpkii/1.0 (compatible; BQ51/1.0)");
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        /** 设置下载地址和文件存放位置 **/
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Ext_InSdk_Curl_Https_Write_Data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        /** 设置连接超时限制 **/
        curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
        /** 设置下载超时限制 **/
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 300);
        /** 设置低速限制：30秒内速度低于 10 bytes/sec 时终止 **/
        curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 10);
        curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 30);

        CURLcode res;
        int cnt = 0;
        while (cnt < 3)
        {
            res = curl_easy_perform(curl);
            if (res != CURLE_OK)
            {
                PRT_ERR(DEF_TAG, "Curl_File_Download download fail: %s,curl again\n", curl_easy_strerror(res));
                cnt++;
                usleep(500 * 1000);
            }
            else
            {
                ret = 0;
                break;
            }
        }
        fclose(fp);
    }
    else
    {
        fprintf(stderr, "Curl_File_Download init fail\n");
    }

    curl_easy_cleanup(curl);
    curl_global_cleanup();

    return ret;
}
